<?php

/**
 * Framework_Module_User_WatchUnlock
 *
 * @author      Ian Szewczyk <roamzero@gmail.com>
 * @copyright   (c) 2007 Ian Szewczyk. All rights reserved.
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package Module
 * @filesource
 */


/**
 * Framework_Module_User_WatchUnlock
 *
 * AKA remote site unlocks itself for watching command
 *
 * @author Ian Szewczyk <roamzero@gmail.com>
 * @package Module
 */
class Framework_Module_User_WatchUnlock extends Framework_Module_User
{
	
	/**
	 * $remoteOwner
	 *
	 * The remote profile owner
	 * 
	 * @access 		public
	 * @var 		array 		$remoteOwner
	 */
	private $remoteOwner = null;

	/**
	 * $from
	 *
	 * @access 		public
	 * @var 		string 		$from		Where is the siteuser originally from?
	 */
	private $from = null;

	/**
     * __construct
     *
     * Initializes the module: sets the default presenter, the allowed
     * conrollers, and the allowed events
     *
     * @access 		public
     * @return 		void
     */
	public function __construct()
	{
		parent::__construct();
		$this->presenter = 'Module';
		$this->validEvents[] = 'confirmViaScript';
		$this->validEvents[] = 'viaRedirect';
		$this->validEvents[] = 'viaScript';
		if (isset($_GET['remoteOwner'])) {
			$this->remoteOwner = htmlentities($_GET['remoteOwner']);
		}
	}

	/**
     * __default
     * 
     *
     * @access 		public
     * @return 		mixed 		boolean true on success, PEAR_Error on failure
     */
	public function __default()
	{
		$this->presenter = 'None';
			
	}

	/**
     * viaRedirect
     * 
     * Prep the watch coming from a redirect
     *
     * @access 		public
     * @return 		mixed 		boolean true on success, PEAR_Error on failure
     */
	public function viaRedirect()
	{
		$this->tplFile = 'WatchUnlock.tpl';
		if (!isset($_GET['from'])) {
			return PEAR::raiseError('Invalid Request: Missing "from" parameter');
		} else {
			$this->from = htmlentities($_GET['from']);
			$this->setData('viaRedirect', true);

			$this->forms['form'] = Framework_Quickform::factory('confirmWatch', 'post', Framework::$request->getHTTPPath().'?from='.$this->from.'&remoteOwner='.$this->remoteOwner, '', null, true);
			// Confirm button
			$this->forms['form']->addElement('submit','btnSubmit','Watch','class="button" id="watchButton"');
			// Cancel button
			$this->forms['form']->addElement('submit','btnCancel','Cancel','class="button" id="cancelButton"');
			if(isset($_GET['viaFrame'])) {
				$this->forms['form']->addElement('hidden','viaFrame', 'true');
			}
			$this->forms['form']->addElement('hidden','from', $from);
			

			// Process form
			if ($this->forms['form']->validate()) {
				$result = $this->forms['form']->process(array($this, 'confirmViaRedirect'));
				return $result;
			} 

		}

	}

	/**
     * confirmViaRedirect
     * 
     * Prep the watch coming from a redirect
     *
     * @access 		public
     * @param		array		$data		Data to process
     * @return 		mixed 		boolean true on success, PEAR_Error on failure
     */
	public function confirmViaRedirect($data)
	{
		if($data['btnSubmit'] && $this->remoteOwner) {
			
			// Check to see if remote owner already exists as a siteuser
			$remoteOwner = explode('@',$this->remoteOwner);
			$this->setData('remoteOwner',$remoteOwner[0]);
			$queryArray = array(
				'sqlKey' => array(
					'select' => 'idSiteUser',
					'where'  => 'userName = ? AND siteDomain =?',
					'get'    => 'one'
							
		  	 	),
			 
				'params' => array($remoteOwner[0],$remoteOwner[1])
			);
			$siteUserTable = Framework_DB::tableFactory('SiteUser');
				
			$id = $siteUserTable->select($queryArray);
			
				
			// if not, load that remote owner and save him or her to the db
			if (!$id) {
				
				require "HTTP/Request.php";
				$req = new HTTP_Request('http://'.$remoteOwner[1].'/'.$remoteOwner[0].'/User/Watch/info');

				$result = $req->sendRequest();
				if (PEAR::isError($result)) {
					$errors[] = 'Network Error: Could not contact site to load owner information';
					$errors[] = $result->getMessage();
				} else {
					$xml = $req->getResponseBody();
					$xml = simplexml_load_string($xml);

					 

					if ($xml->header->type == 'error'){
						$errors[] = 'Error Recieved from site you are currently browsing: '.$xml->message->errorMessage;

					} else {
						// Assume this data is validated
						$siteUserTable->siteDomain = $remoteOwner[1]; // domain
						$siteUserTable->userName = $remoteOwner[0]; // userName
						// Not this data though
						$siteUserTable->avatarURL= strip_tags($xml->message->avatarURL); // avatarURL
						$siteUserTable->blurb  = substr(strip_tags($xml->message->blurb), 0, 350); // blurb

						// Keys are required too
						// TODO: Validate keys

						if (strlen($xml->message->publicKey)){
							$siteUserTable->publicKey = strip_tags($xml->message->publicKey); // publicKey
						} else {
							$errors[] = 'Missing Public Key';
							 
						}

						$id = $siteUserTable->nextId();
						$siteUserTable->idSiteUser = $id;
						$result = $siteUserTable->save();
						if(PEAR::isError($result)) {
							$errors[] = 'Could not save user to watch: Database Error';
						}
					}
				}
			}
			
			// At this point, flag the watch
			if (!count($errors) && ($this->user->userStatus == OWNER_USER_STATUS)){
				
				$friendStatusTable = Framework_DB::tableFactory('FriendStatus');
				$friendStatusTable->load(array('idOwner' => $this->user->idOwner, 'idSiteUser' => $id));
				$friendStatusTable->idOwner = $this->user->idOwner;
				$friendStatusTable->idSiteUser = $id;
				if (!$friendStatusTable->watchedByUser) {
					$friendStatusTable->watchedByUser = 0;
				}
				$friendStatusTable->watchingUser = 1;
				$result = $friendStatusTable->save();

				if(PEAR::isError($result)) {
					$errors[] = 'Could not complete watch: Database Error';
				}
			} else {
				$errors[] = 'Could not complete watch';
			}
				

			if (!count($errors)) {
				$params = array();
				$params['from'] = $this->from;
				if ($data['viaFrame']) {
					$params['viaFrame'] = 'true';
				}
				// Redirect to watch
				Framework_Header::redirect('http://'.$remoteOwner[1].'/'.$remoteOwner[0].'/User/Watch/', $params);
			} else {
				// TODO:: handle errors
				Framework_Header::redirect($this->from);
			}
			
			
		} else if ($data['viaFrame']) {
			    $remoteOwner = explode('@',$this->remoteOwner);
				$params = array();
				$params['from'] = $this->from;
				$params['viaFrame'] = 'true';
				if($data['btnCancel']) {
					$params['cancel'] = 'true';
				}
				Framework_Header::redirect('http://'.$remoteOwner[1].'/'.$remoteOwner[0].'/User/Watch/', $params);
			 
		} else {
			
			//redirect to from
			Framework_Header::redirect($this->from);
		}



	}
	
//	public function viaScript()
//	{
//		$this->tplFile = 'WatchUnlock.tpl';
//		$this->setData('viaScript', true);
//		// verify token
//		if(isset($_COOKIE['Token']) && $this->remoteOwner){
//			$owner = Framework_Owner::singleton();
//			if ($owner->isValid){
//				if($this->verifyToken($owner->pWord, $_SERVER['REMOTE_ADDR'], $owner->privateKey, $_COOKIE['Token'])){
//					// set session watch key
//					$this->session->watchKey = Framework::$util->string_random(5);
//					// set remoteOwner
//					$this->setData('remoteOwner', $this->remoteOwner);
//
//				} else {
//					$errors[] = 'Invalid Token';
//				}
//			} else {
//				$errors[] = 'Remote User Not Found';
//			}
//
//
//		} else {
//			$errors[] = 'Invalid Request';
//		}
//
//		if ($errors) {
//			$this->setData('errors',$errors);
//		}
//
//		return true;
//	}
//
//	public function confirmViaScript()
//	{
//		$this->tplFile = 'WatchUnlockConfirmed.tpl';
//		 
//		if(isset($_GET['watchKey']) && $this->session->watchKey) {
//			if (($_GET['watchKey'] == $this->session->watchKey) && $this->remoteOwner) {
//				// Check to see if remote owner already exists as a siteuser
//				$remoteOwner = explode('@',$this->remoteOwner);
//				$this->setData('remoteOwner',$remoteOwner[0]);
//				$queryArray = array(
//					'sqlKey' => array(
//						'select' => 'idSiteUser',
//						'where'  => 'userName = ? AND domain =?',
//						'get'    => 'one'
//						
//	  	 			),
//				    'params' => array($remoteOwner[0],$remoteOwner[1])
//				);
//				$siteUserTable = Framework_DB::tableFactory('SiteUser');
//					
//				$id = $siteUserTable->select($queryArray);
//					
//				// if not, load that remote owner and save him or her to the db
//				if (!$id) {
//					require "HTTP/Request.php";
//					$req = new HTTP_Request('http://'.$remoteOwner[1].'/'.$remoteOwner[0].'/User/Watch/info');
//
//					$result = $req->sendRequest();
//					if (PEAR::isError($result)) {
//						$errors[] = 'Network Error: Could not contact site to load owner information';
//						$errors[] = $result->getMessage();
//					} else {
//						$xml = $req->getResponseBody();
//						$xml = simplexml_load_string($xml);
//
//						 
//
//						if ($xml->header->type == 'error'){
//							$errors[] = 'Error Recieved from site you are currently browsing: '.$xml->message->errorMessage;
//
//						} else {
//							// Assume this data is validated
//							$siteUserTable->domain = $remoteOwner[1]; // domain
//							$siteUserTable->userName = $remoteOwner[0]; // userName
//							// Not this data though
//							$siteUserTable->avatarURL= strip_tags($xml->message->avatarURL); // avatarURL
//							$siteUserTable->blurb  = strip_tags($xml->message->blurb); // blurb
//
//							// Keys are required too
//							// TODO: Validate keys
//
//							if (strlen($xml->message->publicKey)){
//								$siteUserTable->publicKey = strip_tags($xml->message->publicKey); // publicKey
//							} else {
//								$errors[] = 'Missing Public';
//								 
//							}
//
//
//							$id = $siteUserTable->nextId();
//							$siteUserTable->idSiteUser = $id;
//
//
//
//							$result = $siteUserTable->save();
//							if(PEAR::isError($result))
//							$errors[] = 'Could not save user to watch: Database Error';
//						}
//					}
//				}
//				// At this point, flag the watch
//				if (!count($errors) && !PEAR::isError($result) && ($this->user->userStatus == OWNER_USER_STATUS)){
//					$friendStatusTable = Framework_DB::tableFactory('FriendStatus');
//					$friendStatusTable->load(array('idOwner' => $this->user->idOwner, 'idSiteUser' => $id));
//					$friendStatusTable->idOwner = $this->user->idOwner;
//					$friendStatusTable->idSiteUser = $id;
//					$friendStatusTable->watchingUser = 1;
//					$result = $friendStatusTable->save();
//
//					if(PEAR::isError($result))
//					$errors[] = 'Could not complete watch: Database Error';
//				} else {
//					$errors[] = 'Could not complete watch';
//				}
//					
//			} else {
//				$errors[] = 'Invalid Watch Key Or Missing Owner Parameter';
//			}
//		} else {
//			$errors[] = 'Missing Watch Key';
//		}
//		 
//		if($errors)
//		$this->setData('errors',$errors);
//
//
//		return true;
//	}




}

?>